﻿using System;

namespace SilentOrbit.ProtocolBuffers
{
    public static class Program
    {
        public static int Main(string[] args)
        {
            try
            {
                Options.TryParse(args, (options) => Build(options));
                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                return -1;
            }
        }

        static string GeProtoType(string type)
        {
            switch (type)
            {
                case "double":
                case "float":
                case "int32":
                case "int64":
                case "uint32":
                case "uint64":
                case "sint32":
                case "sint64":
                case "fixed32":
                case "fixed64":
                case "sfixed32":
                case "sfixed64":
                    return "number";
                case "bool":
                    return "boolean";
                case "string":
                    return "string";
                case "bytes":
                    return "(unsupported type: bytes)";
                default:
                    return type;
            }
        }

        public static void Build(Options options)
        {
            var parser = new FileParser();
            var collection = parser.Import(options.InputProto);

            foreach (var pair in collection.Messages)
            {
                string messageName = pair.Key;
                var message = pair.Value;

                Console.WriteLine();
                string messageComments = string.IsNullOrEmpty(message.Comments) ? "" : "@" + message.Comments.Trim();
                Console.WriteLine($"---@class {messageName} {messageComments}");

                foreach (var keyFieldPair in message.Fields)
                {
                    var field = keyFieldPair.Value;
                    string array = field.Rule == FieldRule.Repeated ? "[]" : "";
                    string luaType = GeProtoType(field.ProtoTypeName);

                    string comments = string.IsNullOrEmpty(field.Comments) ? "" : "@" + field.Comments.Trim();
                    Console.WriteLine($"---@field public {field.ProtoName} {luaType}{array} {comments}");
                }
            }
        }
    }
}
